package com.yt.fras.service.impl;


import com.yt.fras.pojo.base.LoginUser;
import com.yt.fras.pojo.entity.Permission;
import com.yt.fras.pojo.entity.User;
import com.yt.fras.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:UserDetailsServiceImpl
 * Package:com.yt.fras.config.impl
 * Description:
 *
 * @date:2021/8/15 18:19
 * @author:yt
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户不能为空");
        }

        User user = userService.queryByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (user != null) {
            List<Permission> permissions = userService.findPermissionByUsername(username);
            permissions.forEach(permission -> {
                grantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionCode()));
            });

        }

        return new LoginUser(user.getId(), user.getUsername(), user.getPassword(), user.getEnabled(), user.getAccountNonExpired(), user.getAccountNonLocked(), user.getCredentialsNonExpired(), grantedAuthorities);
    }

}
